package com.system.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.Iterator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.net.ssl.SSLContext;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.wxpay.util.PayCommonUtil;


public class SSLUtil {
	
	public static SortedMap<String, Object> sslRequest(String certPath,String MCH_ID,String url,String requestXML) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(new FileInputStream(new File(certPath)), MCH_ID.toCharArray());
        /*SSLContext sslcontext = SSLContexts.custom()
                //忽略掉对服务器端证书的校验
                .loadTrustMaterial(new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return true;
                    }
                })*/
                
                //加载服务端提供的truststore(如果服务器提供truststore的话就不用忽略对服务器端证书的校验了)
                //.loadTrustMaterial(new File("D:\\truststore.jks"), "123456".toCharArray(),
                //        new TrustSelfSignedStrategy())
                /*.loadKeyMaterial(keyStore, "cmcc".toCharArray())
                .build();*/
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, MCH_ID.toCharArray()).build(); 
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslConnectionSocketFactory)
                .build();

        try {

            HttpPost httppost = new HttpPost(url);
//            httppost.addHeader("Connection", "keep-alive");
//            httppost.addHeader("Accept", "*/*");
//            httppost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//            httppost.addHeader("Host", "api.mch.weixin.qq.com");
//            httppost.addHeader("X-Requested-With", "XMLHttpRequest");
//            httppost.addHeader("Cache-Control", "max-age=0");
//            httppost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            StringEntity se = new StringEntity(requestXML);  
            httppost.setEntity(se);  

            System.out.println("Executing request " + httppost.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                System.out.println(response.getStatusLine());
                String content = IOUtils.toString(entity.getContent());
                System.out.println("ssl请求返回的内容content:"+content);
                EntityUtils.consume(entity);
		         
	            InputStream in = entity.getContent();
	            SortedMap<String, Object> m = new TreeMap<>();
	            try {
	    			SAXBuilder builder = new SAXBuilder();
	    			Document doc = builder.build(in);
	    			Element root = doc.getRootElement();
	    			List list = root.getChildren();
	    			Iterator it = list.iterator();
	    			while (it.hasNext()) {
	    				Element e = (Element) it.next();
	    				String k = e.getName();
	    				String v = "";
	    				List children = e.getChildren();
	    				if (children.isEmpty()) {
	    					v = e.getTextNormalize();
	    				} else {
	    					v = PayCommonUtil.getChildrenText(children);
	    				}

	    				m.put(k, v);
	    			}

	    			// 关闭流
	    			in.close();
	    		} catch (Exception e1) {
	    			e1.printStackTrace();
	    		}
                return m;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}
